import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { StepTitle } from './../../../shared/components';
import { PasswordResetService } from './service/password-reset.service';
import { I18nService } from '../../../core/i18n/i18n.service';
import { RegionNumber } from 'src/app/model';
import { NzMessageService } from 'ng-zorro-antd';

const StepTitles: StepTitle[] = [
  {
    title: '输入账号',
    translate: 'pages.password.reset.tab.input',
  },
  {
    title: '修改密码',
    translate: 'pages.password.reset.tab.change',
  },
  {
    title: '完成',
    translate: 'pages.password.reset.tab.complete',
  }
];

const passwordValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
  const newPassword = control.get('newPassword');
  const confirmPassword = control.get('confirmPassword');
  if(newPassword && confirmPassword ){

  }
  return newPassword && confirmPassword && newPassword.value !== confirmPassword.value ? { 'passwordError': true } : null;
};

function applyMixins<T>(...baseObject: any[]): T {
  const data: any = {};
  baseObject.forEach(bo => {
    Object.getOwnPropertyNames(bo).forEach(key => {
      data[key] = bo[key];
    });
  });
  return data as T;
}

@Component({
  selector: 'app-password-reset',
  templateUrl: './password-reset.component.html',
  styleUrls: ['./password-reset.component.scss'],
  providers: [
    PasswordResetService
  ]
})
export class PasswordResetComponent implements OnInit {

  private _current = 0;

  stepTitles = StepTitles;
  nzSelectedIndex = 0;
  regionNumbers: RegionNumber[] = [];

  emailForm: FormGroup;
  phoneForm: FormGroup;
  passwordForm: FormGroup;

  account: string;
  accountType: 'email' | 'phone';

  authCodeLable = '发送验证码';

  // @Input()
  set current(_current: number) {
    if (_current >= 2) {
        this.resetPassword();
    } else {
      this._current = _current;
    }
  }

  get current(): number {
    return this._current;
  }

  constructor(
    private fb: FormBuilder,
    private router: Router,
    private passwordResetService: PasswordResetService,
    private i18nService: I18nService,
    private message: NzMessageService,
  ) {
    this.emailForm = this.fb.group({
      email: [null, [Validators.required, Validators.pattern('^[a-zA-Z0-9_\-]{2,}@[a-zA-Z0-9_\-]{2,}(\.[a-zA-Z0-9_\-]+){1,2}$')]],
    });
    this.phoneForm = this.fb.group({
      phone: [null, [Validators.required, Validators.pattern(/^1[34578]\d{9}$/)]],
      regionNumber: [86, [Validators.required]],
    });

    this.passwordForm = this.fb.group({
      authCode: [null, [Validators.required]],
      newPassword: [null, [Validators.required]],
      confirmPassword: [null, [Validators.required, passwordValidator]],
    });
    // { validators: passwordValidator }
    this.passwordForm.setValidators(passwordValidator);

    this.initRegionNumbers();
  }

  formNext(num: number) {
    if (num === 1) {
      this.account = this.emailForm.get('email').value;
      this.current = 1;
      this.accountType = 'email';
      // this.emailForm.reset();
      this.phoneForm.reset();
    } else if (num === 2) {
      this.account = this.phoneForm.get('regionNumber').value + '-' + this.phoneForm.get('phone').value;
      this.current = 1;
      this.accountType = 'phone';
      this.emailForm.reset();
      // this.phoneForm.reset();
    }
  }

  toPage(url: string) {
    this.router.navigateByUrl(url);
  }

  getAuthCodeLable() {
    if (this.authCodeLable === '发送验证码') {
      let num = 60;
      const timmer = setInterval(() => {
        this.authCodeLable = '重新发送(' + num + ')';
        num--;
      }, 1000);
      setTimeout(() => {
        clearInterval(timmer);
        this.authCodeLable = '发送验证码';
      }, 60 * 1000);
      this.sendCodeForRePwd();
    }

  }

  changeLang(lang: string) {
    this.i18nService.changeLang(lang);
  }

  private sendCodeForRePwd() {
    const map = new Map<string, { email: string } | { mobile: string }>();
    map.set('email', { email: this.account });
    map.set('phone', { mobile: this.account });
    const data = map.get(this.accountType);
    this.passwordResetService.sendCodeForRePwd(data).subscribe(res => {
      if (res.status !== 0) {
        this.passwordResetService.error(res);
      }
    }, error => this.passwordResetService.error(error));
  }

  private resetPassword() {
    const data = {
      verifyCode: this.passwordForm.get('authCode').value,
      newPwd: this.passwordForm.get('newPassword').value,
      newConfirmPwd: this.passwordForm.get('confirmPassword').value,
    };
    const map = new Map<string, { email: string } | { mobile: string }>();
    map.set('email', { email: this.account });
    map.set('phone', { mobile: this.account });
    const accountData = map.get(this.accountType);
    const param = applyMixins<{
      verifyCode: string,
      newPwd: string,
      newConfirmPwd: string
    } & ({ mobile: string } | { email: string })>(data, accountData);
    this.passwordResetService.resetPassword(param).subscribe(res => {
      if (res.status === 0) {
        this._current = 2;
      } else {
        this.passwordResetService.error(res);
      }
    }, error => this.passwordResetService.error(error));
  }

  private initRegionNumbers() {
    this.i18nService.getRegionNumbers().subscribe(res => {
      if (res.status === 0) {
        this.regionNumbers = res.data;
      } else {
        this.message.create('error', res.message);
      }
      if (!this.regionNumbers || this.regionNumbers.length === 0) {
        this.message.create('warning', 'region numbers is empty');
      } else {
        // this.seletedRegionNumber = '' + this.regionNumbers[0].number;
        // this.phoneForm.patchValue({ regionNumber: '' + this.regionNumbers[0].number});
      }
    }, error => this.message.create('error', JSON.stringify(error)));
  }

  ngOnInit() {

    // this._current = 2;
  }

}
